<?php
require('../includes/init.php');
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['act'] == 'post_mobile'){
	if($_SESSION[SESSION_PREFIX]['code_send_data'] != $_POST['mobile_code']){
		$res_arr = array(
			'type' => 'err',
			'msg' => '短信验证码不正确',
		);
		exit;
	}
	$sql = "SELECT `user_id` FROM `user` WHERE `mobile`='".$_POST['mobile']."';";
	$user = $db->getRow($sql);
	if(!$user){
		$res_arr = array(
			'type' => 'err',
			'msg' => '抱歉，该手机号未注册',
		);
		exit;
	}

	$sql = "UPDATE `user` SET `password`='".md5($_POST['pwd'])."' WHERE `user_id`='".$user['user_id']."';";
	$db->query($sql);

	$res_arr = array(
		'type' => 'ok',
		'msg' => '重置成功，赶快去登陆吧~',
		'url' => $return_url
	);
	die(json_encode($res_arr));
}
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['act'] == 'post')
{
	$username = trim($_POST['username']);
	$captcha  = $_POST['imgcode'];
	
	$res_arr = array(
		'type' => '',
		'msg'  => '',
		'url'  => ''
	);
	
	if($username=='')
	{
		$res_arr = array(
			'type' => 'err_username',
			'msg' => '邮箱不能为空'
		);
		die(json_encode($res_arr));
	}
	
	//验证码
	require(ROOT_PATH . '/includes/securimage/securimage.php');
    $securimage = new Securimage();
    if ($securimage->check($captcha) == false) {
    	$res_arr = array(
			'type' => 'err_code',
			'msg' => '验证码错误'
		);
		die(json_encode($res_arr));
    }
	
		
	$sql = "SELECT `user_id`,`username`,`email`,`password` FROM `user` WHERE `username`='".$username."' OR `email`='".$username."';";
	$user = $db->getRow($sql);
	//die($user);
	if(!empty($user))
	{
			//发送邮件
			$forget_pwd = rand(10000,999999);
			//随机临时密码，更新到数据库
			$sql = "UPDATE `user` SET `forget_pwd`='".$forget_pwd."' WHERE `username`='".$username."' OR `email`='".$username."';";
			$db->query($sql);
				
			//邮件标题
			$subject = $_SERVER['HTTP_HOST'].'找回密码';
			$to = $user['email'];
		
			//邮件正文
			$message = '尊敬的 <b>'.$user['username'].'</b> 您好！<br />
				您于 '.date("Y").'年'.date("m").'月'.date("d").'日 '.date("H").'时'.date("i").'分'.date("s").'秒 申请找回密码，点击以下连接，即可修改密码：<br />
				<a href="'.WWW_DOMAIN.'/member/findpwd_set.php?v='.$forget_pwd.'&user='.$user['username'].'">点击这里</a>，立即修改密码。<br />
				如果您点击上述链接无效，请将下面的链接复制到浏览器地址栏中访问：<br />
				http://'.WWW_DOMAIN.'/member/findpwd_set.php?v='.$forget_pwd.'&user='.$user['username'].'<br />
				…………………………<br />
				这是一封系统邮件，请不要回复。<br/>
				如非本人操作，请勿理会！<br/>
				';
			
		//@mail($to, $subject, $message, $headers);
		send_mail($user['username'], $to, $subject, $message, 1);
		//验证邮件
			
			$return_url = isset($_POST['return_url'])?$_POST['return_url']:'/';
			$res_arr = array(
				'type' => 'ok',
				'msg' => '邮件已发送，请查收！并按提示完成新密码设置',
				'url' => $return_url
			);
			die(json_encode($res_arr));
		
	}
	else
	{
		$res_arr = array(
			'type' => 'err_username',
			'msg' => '邮箱地址不存在'
		);
		die(json_encode($res_arr));
	}
}
?>
<?php include('../new/header.php');?>

<link href="/css/v1/register.css" rel="stylesheet" type="text/css" />
<script src="/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/js/jquery.form.js"></script>
<script type="text/javascript" src="/js/artDialog4.1.7/artDialog.js?skin=blue"></script>
<style>
    .login_wrap{
        height: 650px;
    }
</style>
<div id="content_body">
  <div class="login_wrap">
    <div class="fm960">
      <div class="logo"> <a href="/" class="mogujie fl" title="<?php echo $cfg_site['web_title'];?>"><?php echo $cfg_site['web_title'];?></a> </div>
      <div class="content">
        <div class="lg_left">
          <h1>找回密码</h1>
          <div class="lg_form">
			<div style="margin-bottom: 33px;    margin-bottom: 25px;width: 100%;overflow: hidden;padding: 0 10px;height: 40px;font-size: 14px;line-height: 40px;">
				<input class="email_find" onclick="emailFind()" style="cursor: pointer;width: 11px;height: 11px;margin-right: 5px !important;" type="radio" name="radio1"  checked="true"/><span style="cursor: pointer;" onclick="emailFind()">邮箱找回</span>
				<input class="mobile_find" onclick="mobileFind()" style="cursor: pointer;width: 11px;height: 11px;margin-right: 5px !important;margin-left: 30px;" type="radio" name="radio1"  style="margin-left: 47px" /><span style="cursor: pointer;" onclick="mobileFind()">手机找回</span>
			</div>
            <form id="myform" action="" method="post">
              <div class="lg_name"> <span>邮&ensp;&ensp;箱：</span>
                <input type="text" placeholder="请输入注册邮箱" value="" name="username" id="username" class="text r3" maxlength="32">
              </div>
              <div class="err_name"><span>请输入注册邮箱</span></div>
              <div class="clear"></div>
              <div class="clear" id="appendimgcheck"></div>
              <div class="lg_chk shouldremove"> <span>验证码：</span>
                <div style="float:left">
                <input style="width: 110px;" id="imgcode" type="text" maxlength="4" name="imgcode" class="text r3" style="border-color: rgb(207, 207, 207);" onkeyup="this.value = this.value.toUpperCase();">
                </div>
                <img id="siimage" style="border: 1px solid #000; margin-right: 15px; margin-left:10px; margin-top:1px; cursor:pointer;" src="../includes/securimage/securimage_show.php?sid=<?php echo md5(uniqid()) ?>" onclick="this.src='../includes/securimage/securimage_show.php?sid='+Math.random()" alt="看不清？换一个" title="看不清？换一个" height="30" align="left" />
            <a tabindex="-1" style="border-style: none;" href="#" title="看不清？换一个" onclick="document.getElementById('siimage').src = '../includes/securimage/securimage_show.php?sid=' + Math.random(); this.blur(); return false"><img style="display: inline;" src="../includes/securimage/images/refresh.png" alt="Reload Image" height="32" width="32" onclick="this.blur()" align="bottom" border="0" /></a>
              </div>
              <div class="clear"></div>
              <div class="lg_login">
                <input type="submit" value=" 找回密码 ">
              </div>
              <input name="act" value="post" type="hidden">
            </form>
			<form id="myform1" action="" method="post" style="display: none;">
              <div class="lg_name"> <span>手&ensp;机&ensp;号：</span>
                <input type="text" placeholder="请输入注册手机号" value="" name="mobile" id="mobile" class="text r3" maxlength="32">
              </div>
              <div class="err_name"><span>请输入注册手机号</span></div>
              <div class="clear"></div>
              <div class="clear" id="appendimgcheck"></div>
              <div class="lg_chk shouldremove"> <span>验&ensp;证&ensp;码：</span>
                <div style="float:left">
                <input style="width: 145px;" id="mobile_code" type="text" maxlength="6" name="mobile_code" class="text r3" style="border-color: rgb(207, 207, 207);">
                </div>
				<span id="send_code_btn" onclick="sendCode()" style="margin-left: 10px;cursor: pointer;border: 1px #cfcfcf solid;color: #666;padding: 0 10px;margin-top: 0px;font-size: 13px;height: 30px;line-height: 29px;width: 87px;text-align: center;">发送验证码</span>
              </div>
              <div class="clear"></div>
			  <div class="lg_name" style="margin-top: 15px;"> <span>新&ensp;密&ensp;码：</span>
                <input type="password" placeholder="请输入新密码" value="" name="pwd" id="pwd" class="text r3" maxlength="32">
              </div>
              <div class="clear"></div>
			  <div class="lg_name" style="margin-top: 15px;"> <span>确认密码：</span>
                <input type="password" placeholder="请再次输入密码" value="" name="sure_pwd" id="sure_pwd" class="text r3" maxlength="32">
              </div>
              <div class="clear"></div>
              <div class="lg_login" style="margin-top: 20px;margin-left: 78px;">
                <input type="submit" value=" 找回密码 ">
              </div>
              <input name="act" value="post_mobile" type="hidden">
            </form>
          </div>
        </div>
        <div class="lg_right">
          <h2>注册</h2>
          <span style="margin-left:40px;">还没有账号？</span> <a style="margin-left:40px;" class="reg" href="register.php"></a> </div>
        <input type="hidden" value="" id="isban">
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
$(document).ready(function() {
	var options = {
		dataType:  'json',
        beforeSubmit:  validate,
        success:       showResponse
    }; 
 
    $('#myform').ajaxForm(options);
	var options1 = {
		dataType:  'json',
        beforeSubmit:  validate1,
        success:       showResponse
	}
    $('#myform1').ajaxForm(options1);
});


function validate1(formData, jqForm, options)
{
	if ($('#mobile').val() == '')
	{
		art.dialog({
			id: 'memberLoginMsg',
			title: '错误提示',
			content: '手机号不能为空！',
			lock: true,
			opacity: 0.3,
			ok:function(){
				$('#mobile').focus();
			}
		});
        return false; 
    }	
		
	if ($('#mobile_code').val().length != 6)
	{
		art.dialog({
			id: 'memberLoginMsg',
			title: '错误提示',
			content: '验证码必须是6位有效的数字或字符！',
			lock: true,
			opacity: 0.3,
			ok:function(){
				$('#mobile_code').focus();
			}
		});
        return false; 
    }

	if ($('#pwd').val() == '')
	{
		art.dialog({
			id: 'memberLoginMsg',
			title: '错误提示',
			content: '密码不能为空',
			lock: true,
			opacity: 0.3,
			ok:function(){
				$('#pwd').focus();
			}
		});
        return false; 
    }


	if ($('#pwd').val() != $('#sure_pwd').val())
	{
		art.dialog({
			id: 'memberLoginMsg',
			title: '错误提示',
			content: '两次密码不一致',
			lock: true,
			opacity: 0.3,
			ok:function(){
				$('#sure_pwd').focus();
			}
		});
        return false; 
    }
	
	return true;
}

function validate(formData, jqForm, options)
{
	if ($('#username').val() == '')
	{
		art.dialog({
			id: 'memberLoginMsg',
			title: '错误提示',
			content: '邮箱不能为空！',
			lock: true,
			opacity: 0.3,
			ok:function(){
				$('#username').focus();
			}
		});
        return false; 
    }	
		
	if ($('#imgcode').val().length != 4)
	{
		art.dialog({
			id: 'memberLoginMsg',
			title: '错误提示',
			content: '验证码必须是4位有效的数字或字符！',
			lock: true,
			opacity: 0.3,
			ok:function(){
				$('#imgcode').focus();
			}
		});
        return false; 
    }
	
	return true;
}

function showResponse(data)
{
	if(data.type == 'ok')
	{
		art.dialog({
			id: 'memberLoginMsg',
			title: '系统提示',
			content: data.msg,
			lock: true,
			opacity: 0.3,
			close: function () {
    			window.location = "/new/index.php";
    		}
		}).time(1);
		return;
	}
	else
	{
		art.dialog({
			id: 'memberLoginMsg',
			title: '错误提示',
			content: data.msg,
			lock: true,
			opacity: 0.3,
			ok:function(){				
				switch (data.type)
				{
					default:
						break;
				};
			}//ok
		});
        return false; 
	}
}
function emailFind(){
	$(".email_find").attr("checked", true)
	$('#myform').show();
	$('#myform1').hide();
}
function mobileFind(){
	$(".mobile_find").attr("checked", true)
	$('#myform').hide();
	$('#myform1').show();
}
function sendCode(){
	if($("#send_code_btn").text() != "发送验证码"){
		art.dialog({
			id: 'memberLoginMsg',
			title: '错误提示',
			content: '请稍后再试',
			lock: true,
			opacity: 0.3,
			ok:function(){
				$('#mobile').focus();
			}
		});
        return false; 
	}
	if ($('#mobile').val() == '')
	{
		art.dialog({
			id: 'memberLoginMsg',
			title: '错误提示',
			content: '手机号不能为空！',
			lock: true,
			opacity: 0.3,
			ok:function(){
				$('#mobile').focus();
			}
		});
        return false; 
    }	
	if(!validatePhoneNumber($('#mobile').val())){
		art.dialog({
			id: 'memberLoginMsg',
			title: '错误提示',
			content: '手机格式不正确',
			lock: true,
			opacity: 0.3,
			ok:function(){
				$('#mobile').focus();
			}
		});
        return false; 
	}

	jQuery.ajax({
		type : "get",
		url : "/ajax/send_code.php?act=verify&mobile="+$("#mobile").val(),
		success : function(obj) {
			if(obj == "1") {
				$("#send_code_btn").text(59);
				var s = setInterval(() => {
					if ($("#send_code_btn").text() == 1){
						$("#send_code_btn").text("发送验证码")
						clearInterval(s)
						return
					}
					var h = $("#send_code_btn").text($("#send_code_btn").text() - 1)
				}, 1000);
			}else if(obj == "0"){
				art.dialog({
					id: 'memberLoginMsg',
					title: '错误提示',
					content: '短信发送失败，请重新获取校验码',
					lock: true,
					opacity: 0.3,
					ok:function(){
						$('#mobile').focus();
					}
				});
			}else if(obj == "-1") {
				art.dialog({
					id: 'memberLoginMsg',
					title: '错误提示',
					content: '抱歉，该手机号未注册',
					lock: true,
					opacity: 0.3,
					ok:function(){
						$('#mobile').focus();
					}
				});
			}else if(obj == "-2") {
				art.dialog({
					id: 'memberLoginMsg',
					title: '错误提示',
					content: '1分钟内仅能获取一次校验码，请稍后重试',
					lock: true,
					opacity: 0.3,
					ok:function(){
						$('#mobile').focus();
					}
				});
			}else if(obj == "-3") {
				art.dialog({
					id: 'memberLoginMsg',
					title: '错误提示',
					content: '您获取短信校验码的次数已达上限，请于24小时后重试',
					lock: true,
					opacity: 0.3,
					ok:function(){
						$('#mobile').focus();
					}
				});
			}else if(obj == "-4") {
				art.dialog({
					id: 'memberLoginMsg',
					title: '错误提示',
					content: '您的手机号已验证过，请更换手机号码',
					lock: true,
					opacity: 0.3,
					ok:function(){
						$('#mobile').focus();
					}
				});
			}else{
				art.dialog({
					id: 'memberLoginMsg',
					title: '错误提示',
					content: '网络连接超时，请重新获取校验码',
					lock: true,
					opacity: 0.3,
					ok:function(){
						$('#mobile').focus();
					}
				});
			}
		},
    	error : function() {
			art.dialog({
				id: 'memberLoginMsg',
				title: '错误提示',
				content: '网络连接超时，请您稍后重试',
				lock: true,
				opacity: 0.3,
				ok:function(){
					$('#mobile').focus();
				}
			});
    	}
	});
}

function validatePhoneNumber(phoneNumber) {
  if (phoneNumber.length !== 11) {
      return false;
  }
  var reg = /^1\d{10}$/;
  return reg.test(phoneNumber);
}

</script>

<?php include('../new/footer.php');?>